package cn.itcast.web.controller.system;

import cn.itcast.common.utils.Encrypt;
import cn.itcast.common.utils.MailUtil;
import cn.itcast.domain.system.Role;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.DeptService;
import cn.itcast.service.system.RoleService;
import cn.itcast.service.system.UserService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.producer.MailProducer;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MailProducer mailProducer;



    //跳转列表页面 分页
    @RequestMapping("/list")
    public String list(HttpServletRequest request,@RequestParam(defaultValue = "1") int page , @RequestParam(defaultValue = "10") int size){
        //1.调用service查询
        String companyId = "1";
        PageInfo info = userService.findAll(page,size,companyId);
        //2.将分页结果存入request域
         request.setAttribute("page",info);
        return "system/user/user-list";
    }

    //进入新增页面
    @RequestMapping("/toAdd")
    public String toAdd(HttpServletRequest request){
        //1.调用service查询所有部门
        List deptList = deptService.findAll(getLoginCompanyId());
        //2.将部门集合存入request中
        request.setAttribute("deptList" ,deptList);
        return "system/user/user-add";
    }

    //新增 或 修改部门
    @RequestMapping("/edit")
    public String edit(User user) throws  Exception{
        //设置所属部门的企业和id名称
        user.setCompanyId("1");
        user.setCompanyName("传智播客");
        if (StringUtils.isEmpty(user.getId())){
            //如果传递的对象中没有id   保存

            //获取加密之前的密码进行邮箱发送
            String myPassword = user.getPassword();
            //保存的时候，设置用户密码加密 (加盐salt)
            String password = Encrypt.md5(user.getPassword(),user.getEmail());
            //用户保存完成给用户邮箱发送 用户名、密码、登录地址
            String to = user.getEmail();
            String subject = "欢迎使用SaaS系统";
            String content = "尊敬的用户"+user.getUserName()+",您好。访问URL=http://localhost:8080/,访问邮箱="+to+"访问密码="+myPassword;

            Map map = new HashMap<>();
            map.put("to",to);
            map.put("subject",subject);
            map.put("content",content);

            mailProducer.send("mail.send",map);
            //MailUtil.sendMsg(to,subject,content);

           userService.save(user);
        }else{
            //如果传递的对象中有id   修改
            userService.update(user);
        }
        return "redirect:/system/user/list.do";
    }

    //跳转更新页面 进行数据回显
    @RequestMapping("toUpdate")
    public String toUpdate(String id,HttpServletRequest request) {
        //1.根据id查询用户
        User user = userService.findById(id);
        //2.存入request域中‘
        request.setAttribute("user", user);
        //3.查询所有用户列表，构造下拉框数据
        List deptList = userService.findAll(getLoginCompanyId());
        request.setAttribute("deptList",deptList);
        return "system/user/user-update";
    }

    //删除
    @RequestMapping("/delete")
    public String delete(String id){
        userService.delete(id);
        return "redirect:/system/user/list.do";
    }

    /**
     *  用户通过点击角色发送请求
     */
    @RequestMapping("/roleList")
    public String roleList(String id){
        //根据id查询用户
        User user = userService.findById(id);
        request.setAttribute("user",user);
        //查询所有的角色
        List roleList = roleService.findAll(getLoginCompanyId());
        request.setAttribute("roleList",roleList);
        //根据用户id查询用户所具有的角色列表
        List<Role> userRoles = roleService.findByUserId(id);
        //构造当前用户所具有角色id的字符串（以 "，"隔开）
        StringBuilder builder = new StringBuilder();
        for (Role userRole : userRoles) {
            builder.append(userRole.getId());
            builder.append(",");
        }
        request.setAttribute("userRoleStr",builder.toString());
        return "system/user/user-role";
    }

    /**
     * 1.获取页面参数（用户id，和勾选的角色id的数组）
     * 2.调用service完成角色分配
     * 3.返回列表
     */

    @RequestMapping("/changeRole")
    public String changeRole(String userid,String[] roleIds){
        userService.changeRole(userid,roleIds);
        return "redirect:/system/user/list.do";
    }


}
